package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.faction.FactionAltarRobModel
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryFactionAltarResponse
import com.promise.jokerdream.response.pc.QueryFactionAltarRobResponse
import com.promise.jokerdream.response.pc.SpinFactionAltarWheelResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 帮派祭坛工作
class FactionAltarWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "帮派祭坛"

    override val priority: Int
        get() = 8

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }
    
    // 黑名单：存储返回-1014错误码的帮派ID
    private val blacklist = mutableSetOf<Int>()

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询帮派祭坛信息
            val queryResult = gameApi.queryFactionAltar()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processFactionAltar(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 帮派祭坛状态枚举
     */
    private enum class AltarState {
        HANDLE_PENDING_ACTION,  // 处理未完成的动作
        FREE_WHEEL,            // 免费转盘
        PAID_WHEEL,            // 转转券转盘
        COMPLETED              // 完成
    }

    /**
     * 处理帮派祭坛逻辑 - 状态机模式
     */
    private suspend fun processFactionAltar(response: QueryFactionAltarResponse): WorkResult {
        var currentResponse = response
        var currentState = determineInitialState(currentResponse)
        val maxIterations = 100
        var iterationCount = 0

        while (currentState != AltarState.COMPLETED && iterationCount < maxIterations) {
            iterationCount++

            when (currentState) {
                AltarState.HANDLE_PENDING_ACTION -> {
                    currentState = handlePendingActionState(currentResponse)
                    if (currentState == AltarState.HANDLE_PENDING_ACTION) {
                        // 重新查询状态
                        val newQueryResult = gameApi.queryFactionAltar()
                        newQueryResult.foldWithApiException(
                            onSuccess = { newResponse ->
                                currentResponse = newResponse
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                return WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    }
                }

                AltarState.FREE_WHEEL -> {
                    currentState = handleFreeWheelState(currentResponse)
                    if (currentState == AltarState.FREE_WHEEL) {
                        // 重新查询状态
                        val newQueryResult = gameApi.queryFactionAltar()
                        newQueryResult.foldWithApiException(
                            onSuccess = { newResponse ->
                                currentResponse = newResponse
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                return WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    }
                }

                AltarState.PAID_WHEEL -> {
                    currentState = handlePaidWheelState(currentResponse)
                    if (currentState == AltarState.PAID_WHEEL) {
                        // 重新查询状态
                        val newQueryResult = gameApi.queryFactionAltar()
                        newQueryResult.foldWithApiException(
                            onSuccess = { newResponse ->
                                currentResponse = newResponse
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                return WorkResult.Success // 转转券用完或出错时结束
                            }
                        )
                    }
                }

                AltarState.COMPLETED -> {
                    break
                }
            }
        }

        if (iterationCount >= maxIterations) {
            historyManager.addHistory(name, "达到最大迭代次数，可能存在无限循环")
        }

        return WorkResult.Success
    }

    /**
     * 确定初始状态
     */
    private fun determineInitialState(response: QueryFactionAltarResponse): AltarState {
        return when {
            response.currentActionId != 0 -> AltarState.HANDLE_PENDING_ACTION
            response.leftFreeWheelTimes > 0 -> AltarState.FREE_WHEEL
            response.zhuanZhuanQuanNum > 0 -> AltarState.PAID_WHEEL
            else -> AltarState.COMPLETED
        }
    }

    /**
     * 处理未完成动作状态
     */
    private suspend fun handlePendingActionState(response: QueryFactionAltarResponse): AltarState {
        val actionResult = handleCurrentAction(response.currentActionId)
        return if (actionResult is WorkResult.Success) {
            // 动作执行成功，检查下一步状态
            determineInitialState(response)
        } else {
            AltarState.COMPLETED // 执行失败，结束
        }
    }

    /**
     * 处理免费转盘状态
     */
    private suspend fun handleFreeWheelState(response: QueryFactionAltarResponse): AltarState {
        val spinResult = gameApi.spinFactionAltarWheel()
        spinResult.foldWithApiException(
            onSuccess = { spinResponse ->
                val msg = spinResponse.getDescription()
                if (msg.isNotEmpty()) {
                    historyManager.addHistory(name, msg)
                }
                handleSpinResult(spinResponse)
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                return AltarState.COMPLETED
            }
        )

        // 检查是否还有免费次数
        return if (response.leftFreeWheelTimes > 1) {
            AltarState.FREE_WHEEL // 继续免费转盘
        } else {
            // 免费次数用完，检查下一步状态
            when {
                response.zhuanZhuanQuanNum > 0 -> AltarState.PAID_WHEEL
                else -> AltarState.COMPLETED
            }
        }
    }

    /**
     * 处理转转券转盘状态
     */
    private suspend fun handlePaidWheelState(response: QueryFactionAltarResponse): AltarState {
        val spinResult = gameApi.spinFactionAltarWheel()
        spinResult.foldWithApiException(
            onSuccess = { spinResponse ->
                val msg = spinResponse.getDescription()
                if (msg.isNotEmpty()) {
                    historyManager.addHistory(name, msg)
                }
                handleSpinResult(spinResponse)
            },
            onFailure = { code, msg ->
                // 1009是转转券用完
                val innerCode = if (code == -1009) 0 else code
                historyManager.addHistory(name, msg, innerCode)
                return AltarState.COMPLETED // 转转券用完或出错时结束
            }
        )

        // 继续转转券转盘
        return AltarState.PAID_WHEEL
    }

    /**
     * 处理当前未完成的动作
     */
    private suspend fun handleCurrentAction(actionId: Int): WorkResult {
        return when (actionId) {
            1003 -> {
                // 需要掠夺，查询掠夺信息并执行
                val robResult = gameApi.queryFactionAltarRob()
                robResult.foldWithApiException(
                    onSuccess = { robResponse ->
                        executeRob(robResponse)
                        WorkResult.Success
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                        WorkResult.Failure(Exception(msg), msg)
                    }
                )
            }
            else -> {
                WorkResult.Success
            }
        }
    }

    /**
     * 处理转盘结果
     */
    private suspend fun handleSpinResult(spinResponse: SpinFactionAltarWheelResponse) {
        val actionId = spinResponse.actionId

        if (actionId == 1003) {
            // 需要掠夺，查询掠夺信息
            val robResult = gameApi.queryFactionAltarRob()
            robResult.foldWithApiException(
                onSuccess = { robResponse ->
                    executeRob(robResponse)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        } else if (actionId == 1004) {
            // 需要偷取，查询掠夺信息
            val robResult = gameApi.queryFactionAltarRob()
            robResult.foldWithApiException(
                onSuccess = { robResponse ->
                    executeSteal(robResponse)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }
    }

    /**
     * 选择掠夺目标，按优先级：enemies > revengeTargets > randomFaction
     * 过滤掉黑名单中的目标
     */
    private fun selectRobTargets(robResponse: QueryFactionAltarRobResponse): List<FactionAltarRobModel> {
        val targets = mutableListOf<FactionAltarRobModel>()

        // 优先级1：宣战帮派
        targets.addAll(robResponse.enemies)

        // 优先级2：复仇帮派
        targets.addAll(robResponse.revengeTargets)

        // 优先级3：随机帮派
        if (robResponse.randomFaction.id != 0) {
            targets.add(robResponse.randomFaction)
        }

        return targets.filter { it.id !in blacklist }
    }

    /**
     * 执行掠夺，会尝试所有可用目标直到成功
     */
    private suspend fun executeRob(robResponse: QueryFactionAltarRobResponse) {
        val targets = selectRobTargets(robResponse)

        if (targets.isEmpty()) {
            return
        }

        // 按优先级尝试每个目标
        for (target in targets) {
            val robResult = gameApi.robFactionAltar(target.id)
            robResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                    return // 成功则退出
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    if (code == -1014) {
                        blacklist.add(target.id)
                    }
                    // 继续尝试下一个目标
                }
            )
        }

        historyManager.addHistory(name, "掠夺其他帮派异常", -101)
    }

    /**
     * 执行偷取，会尝试所有可用目标直到成功
     */
    private suspend fun executeSteal(robResponse: QueryFactionAltarRobResponse) {
        val targets = selectRobTargets(robResponse)

        if (targets.isEmpty()) {
            return
        }

        // 按优先级尝试每个目标
        for (target in targets) {
            val robResult = gameApi.stealFactionAltar(target.id)
            robResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                    return // 成功则退出
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    if (code == -1014) {
                        blacklist.add(target.id)
                    }
                    // 继续尝试下一个目标
                }
            )
        }

        historyManager.addHistory(name, "偷取其他帮派异常", -101)
    }
}